package taskrunner

import (
	"GoStreamVideoWebsite/scheduler/dbops"
	"errors"
	"log"
	"sync"
)

func VideoClearDispatcher(dc dataChan) error {
	res, err := dbops.ReadVideoDeletionRecord(3)
	if err != nil {
		log.Printf("Video clear dispatcher  error %v", err)
		return err
	}
	if len(res) == 0 {
		return errors.New("All tasks finished")
	}
	for _, item := range res {
		dc <- item.VideoId
	}
	return nil
}

func VideoClearExecutor(dc dataChan) error {
	var errMap sync.Map
	var wg sync.WaitGroup
	var err error
forloop:
	for true {
		select {
		case vid := <-dc:
			go func(vid interface{}) { //开启go线程去删除内容
				wg.Add(1)
				if err := dbops.DelVideoDeletionRecord(vid.(string)); err != nil {
					errMap.Store(vid, err)
				}
				wg.Done()
			}(vid)
		default:
			break forloop
		}
	}
	wg.Wait()
	errMap.Range(func(key, value interface{}) bool {
		err = value.(error)
		if err != nil {
			return false
		}
		return true
	})
	return err
}
